from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
from django.views import View

from myapp.models import User
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
#导入加密库
import hashlib
#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io

import requests

#导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

#导入原生sql模块
from django.db import connection

import jwt

#导入redis数据库
import redis

#导入时间模块
import time

#导入公共目录变量
from mydjango.settings import BASE_DIR

#导包
from django.db.models import Q,F

#导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid



import time
import hmac
import base64
from hashlib import sha256
import urllib

#构造钉钉回调方法
def ding_back2(request):

    #获取code
    code = request.GET.get("code")

    t = time.time()
    #时间戳
    timestamp = str((int(round(t * 1000))))
    appSecret ='ly-AzMKMmCKQP3geaILT_An32kEfKO3HeOtApy5CgKwjytevVZC0WYsT2gxMB160'
    #构造签名
    signature = base64.b64encode(hmac.new(appSecret.encode('utf-8'),timestamp.encode('utf-8'), digestmod=sha256).digest())
    #请求接口，换取钉钉用户名
    payload = {'tmp_auth_code':code}
    headers = {'Content-Type': 'application/json'}
    res = requests.post('https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature='+urllib.parse.quote(signature.decode("utf-8"))+"&timestamp="+timestamp+"&accessKey=dingoaukgkwqknzjvamdqh",data=json.dumps(payload),headers=headers)

    res_dict = json.loads(res.text)
    # print(res_dict)
    # return HttpResponse(res.text)

    # 判断是否用钉钉登录过
    user = User.objects.filter(username=str(res_dict['user_info']['nick'])).first()

    ding_id = ''
    user_id = ''

    if user:
        # 代表曾经登录过
        ding_id = user.username
        user_id = user.id
    else:
        # 自动创建账号
        user = User(username=str(res_dict['user_info']['nick']),password='',type=0)
        # 保存
        user.save()

        # 查询用户id
        user = User.objects.filter(username=str(res_dict['user_info']['nick'])).first()

        ding_id = str(res_dict['user_info']['nick'])
        user_id = user.id
    # 跳转操作
    return redirect("http://localhost:8080/?dduser=" + str(ding_id) + '&uid=' + str(user_id))


  # 登录接口
class Login2(APIView):
    def get(self,request):
        # 接收参数
        username = request.GET.get('username','null')
        password = request.GET.get('password','null')

        # 查询数据
        user = User.objects.filter(username=username,password=make_password(password)).first()

        if user:
            res = {}
            res['code'] = 200
            res['message'] = '登录成功'
            res['username'] = user.username
            res['uid'] = user.id
            return Response(res)
        else:
            res = {}
            res['code'] = 405
            res['message'] = '你的用户名或者密码错误'
            return Response(res)
# md5加密方法
def make_password(mypass):
    # 生成MD5对象
    md5 = hashlib.md5()
    # 定义机密对象
    sign_str = str(mypass)
    # 转码
    sign_utf8 = sign_str.encode(encoding='utf-8')
    # 加密
    md5.update(sign_utf8)
    # 生成密钥串
    md5_server = md5.hexdigest()

    return md5_server

  # 注册模块
class Register2(APIView):
    def get(self,request):
        # 接收参数
        username = request.GET.get('username','null')
        password = request.GET.get('password','null')

        # 排重
        user = User.objects.filter(username=username).first()

        if user:
            res = {}
            res['code'] = 405
            res['message'] = '该用户名已存在'
            return Response(res)
        # 入库
        user = User(username=username,password=make_password(password))
        user.save()

        res = {}
        res['code'] = 200
        res['message'] = '注册成功'

        return Response(res)
